#!/usr/bin/python
import sys,os, types
from mbbs_api import mbbs_api
from yaps import yaps
import version
import re

class mbbsh:
    def __init__(self,stdout,stdin,stderr):
        sys.stdout = stdout
        sys.stdin = stdin
        sys.stderr = stderr
        plugindir = os.path.join(os.getcwd(), "plugins")
        
        if os.path.exists(plugindir):
            pass
        else:
            os.mkdir("plugins")
        
        self.mbbs = yaps()
        self.mbbs.setParent(self)
        self.mbbs.loadPlugins("plugins")
        self.mbbs.createInstances()
            
        self.mbbs.registerFunction(self.execute)
        self.mbbs.registerFunction(self.mbbshversion)
        self.mbbs.registerFunction(self.exit)
        #mbbs_api.__init__(self)
        
        print "MBBSH Version: %s" % self.mbbs.mbbshversion()
        print "Plugin directory: %s" % plugindir
        print "Loaded plugins: ", 
        for i in self.mbbs.imported_modules:
            print "%s " % i.__name__
        print
        
    def mbbshversion(self, param=""):
        return(version.version())
        
    def exit(self, param=""):
      sys.exit(0)
      
    def execute(self,cmdstr):
        cmdstr = self.mbbs.replacevars(cmdstr)
        cmd,param = self.divideCmdString(cmdstr)
        cmd = cmd.lower().strip()
        ret = ""
        if cmd != "":
            mcmd = "ret = self.mbbs.%s(\"%s\")" % ( cmd, param)
            debug = 1
            if debug==1:
                exec(mcmd)
                if ret==None:
                    ret = ""
            else:
                try:
                    exec(mcmd)
                    if ret==None:
                        ret = ""
                except:
                    os.system(cmdstr)
        return(ret)
    
    def replaceVars(self, mstr):
      regexp = re.compile(r"""(%{)([^}]*)(})""")
      res = regexp.findall(mstr)
      for i in res:
          try:
              replstr = self.vars[i[1]]
          except:
              try:
                  replstr = os.environ[i[1]]
              except:
                  replstr = ""
          
          srchstr = "%%{%s}" % i[1]
          mstr = mstr.replace(srchstr, replstr)
      
      return(mstr)
    
    def convertListToString(self, mlist):
        mstr = ""
        for i in mlist:
            mstr += "%s " % i
            
        return(mstr)
        
    def divideCmdString(self, cmdStr):
        cmd= ""
        paramStr=""
        if len(cmdStr.split())>=1:
            cmd = cmdStr.split()[0]
        if len(cmdStr.split())>=2:
            paramStr = self.convertListToString(cmdStr.split()[1:])
        return(cmd, paramStr)
    
    
def printres(res):
        if res!="":
            if type(res)==types.DictionaryType:
                for i in res.keys():
                    print "%s: %s" % (i, res[i])
            elif type(res)==types.ListType:
                for i in res:
                    if type(i)==types.ListType:
                        mstr = ""
                        for q in i:
                            mstr+="%s\t" % q
                        print mstr
                    else:
                        print i
            else:
                print res
    
    
def main():
    mymbbs = mbbsh(sys.stdout,sys.stdin,sys.stderr)
    #mymbbs.startup()
    res = ""
    if len(sys.argv) >= 2:
      cmd = mymbbs.convertListToString(sys.argv[1:])
      res =  mymbbs.execute(cmd)
      printres(res)
      
    else:
      cmd = ""
      while 1:
        cwd = os.getcwd()
        sys.stdout.write("MBBS %s > " % cwd)
        cmd = sys.stdin.readline()
        if cmd=="":
          break
        res = mymbbs.execute(cmd)
        printres(res)
              
if __name__ == "__main__":
    main()
    
